package com.teemor.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teemor.auth.bean.po.User;
import com.teemor.auth.bean.po.UserRole;
import com.teemor.auth.bean.vo.req.UserLoginReq;
import com.teemor.auth.bean.vo.rsp.UserLoginRsp;
import com.teemor.auth.bean.vo.rsp.VerifyRsp;
import com.teemor.auth.service.UserRoleService;
import com.teemor.auth.service.UserService;
import com.teemor.common.bean.utils.BeanConvertor;
import com.teemor.common.bean.utils.RandomValidateCodeUtil;
import com.teemor.common.bean.utils.UUIDUtils;

import com.teemor.common.bean.utils.enums.DataStatus;
import com.teemor.common.bean.utils.enums.ResultCode;
import com.teemor.common.bean.utils.excption.TeemorException;
import com.teemor.common.bean.utils.redis.RedisUtils;
import com.teemor.common.bean.utils.tmpl.BaseController;
import com.teemor.common.bean.utils.tmpl.ResponseBen;
import com.teemor.open.openauth.AuthUtils;
import com.teemor.open.openauth.model.AuthUserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/6/2 15:15
 */
@RequestMapping("/auth")
@RestController
@Slf4j
@Api("权限系统")
public class AuthController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;

    @PostMapping(value = "/refresh")
    @ApiOperation(value = "刷新token")
    public ResponseBen<UserLoginRsp> refreshToken(@RequestParam String refreshToken) {
        AuthUserModel authUserModel = Optional.ofNullable(AuthUtils.refreshToken(refreshToken)).orElseThrow(() -> new TeemorException(ResultCode.NOTLOGIN));
        UserLoginRsp userLoginRsp = BeanConvertor.convertBean(authUserModel, UserLoginRsp.class);
        return returnSuccessObject(userLoginRsp);
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录")
    public ResponseBen<UserLoginRsp> login(@RequestBody @Validated UserLoginReq req) {
        ResponseBen<UserLoginRsp> responseBen = new ResponseBen<>();
//        Optional.ofNullable(RedisUtils.getString(req.getCodeToken()))
//                .filter(code -> req.getCode().equals(code))
//                .orElseThrow(() -> new TeemorException(ResultCode.VERIFY_ERROR));

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("phone", req.getAccount()).or()
                .eq("email", req.getAccount());
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            responseBen.setCode(ResultCode.ACCOUNT_NOT_EXISTS);
        } else {
            String pwdMd5 = DigestUtils.md5Hex(req.getPwd());
            if (pwdMd5.equals(user.getPwd())) {
                List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>()
                        .eq("status", DataStatus.USE.value())
                        .eq("user_id", user.getUserId()));
                List<Integer> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
                String token = UUIDUtils.generateUuid();
                String refreshToken = UUIDUtils.generateUuid();
                UserLoginRsp userLoginRsp = new UserLoginRsp();
                userLoginRsp.setToken(token);
                userLoginRsp.setAvatar(user.getAvatar());
                userLoginRsp.setUserId(user.getUserId());
                userLoginRsp.setUserName(user.getUserName());
                userLoginRsp.setRefreshToken(refreshToken);
                AuthUserModel authUserModel = BeanConvertor.convertBean(userLoginRsp, AuthUserModel.class);
                authUserModel.setRoles(roleIds);
                AuthUtils.cacheToken(authUserModel);
                responseBen.setData(userLoginRsp);
            } else {
                responseBen.setCode(ResultCode.PASSWORD_ERROR);
            }
        }
        return responseBen;
    }

    @GetMapping("/getVerify")
    @ApiOperation("获取验证码")
    public ResponseBen<VerifyRsp> getVerify() {
        try {
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            Map<String, String> codeMap = randomValidateCode.getRandcode();//输出验证码图片方法
            String code = codeMap.get("code");
            String codeToken = UUID.randomUUID().toString();
            RedisUtils.setObjectAndTime(codeToken, code, 60 * 5);
            VerifyRsp verifyRsp = new VerifyRsp();
            verifyRsp.setImg(codeMap.get("img"));
            verifyRsp.setToken(codeToken);
            return returnSuccessObject(verifyRsp);
        } catch (Exception e) {
            log.error("获取验证码失败 ", e);
        }
        return returnFailedObject("获取验证码失败");
    }

    @GetMapping("/testAuthModel")
    public ResponseBen<AuthUserModel> testAuthModel(@RequestParam String token) {
        return returnSuccessObject(AuthUtils.getUser(token));
    }
}
